package character.sprite.gui;

import java.awt.Color;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.TransferHandler;

import character.sprite.model.CharacterStyle;
import data.ObjectDatabase;

public class CharacterStyleDropZone extends JLabel {

	private static final long serialVersionUID = -8055958396210902733L;

	private String styleType, styleGUID, spriteGUID;

	public CharacterStyleDropZone(String styleType, String spriteGUID) {
		super();

		setBorder(BorderFactory.createLineBorder(Color.BLACK, 3));
		this.styleType = styleType;
		this.spriteGUID = spriteGUID;
		this.styleGUID = CharacterStyle
				.getDefaultStyleForType(styleType);
		this.setTransferHandler(new DropZoneTransferHandler());
		this.setHorizontalAlignment(JLabel.CENTER);

		CharacterStyle style = (CharacterStyle) ObjectDatabase.getInstance()
				.getEditorObject(CharacterStyle.class.getCanonicalName(),
						styleGUID);
		setIcon(new ImageIcon(style.getThumbnailImage()));
	}

	class DropZoneTransferHandler extends TransferHandler {

		private static final long serialVersionUID = -5822482582979772714L;

		public boolean canImport(TransferHandler.TransferSupport info) {
			try {
				String s = (String) info.getTransferable().getTransferData(
						DataFlavor.stringFlavor);
				String[] transferData = s.split("::");
				return transferData[1].equals(styleType);
			} catch (UnsupportedFlavorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}

		public boolean importData(TransferHandler.TransferSupport info) {
			if (!info.isDrop()) {
				return false;
			}
			try {
				styleGUID = (String) info.getTransferable()
						.getTransferData(DataFlavor.stringFlavor);
				CharacterStyle style = (CharacterStyle) ObjectDatabase
						.getInstance().getEditorObject(
								CharacterStyle.class.getCanonicalName(),
								styleGUID);
				setIcon(new ImageIcon(style.getThumbnailImage()));

				CharacterSpriteDatabase.getInstance().setSpriteStyle(
						CharacterSpriteBuilder.spriteName, styleType,
						style.getGUID());
			} catch (UnsupportedFlavorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}

	}

}
